<?php

require('../../public/common.php');

checkLogin();

if (empty($_POST['nick'])) {

    die(json_encode(array("code" => 1,"msg" => "昵称不能为空")));

} else if (empty($_POST['msg'])) {

    die(json_encode(array("code" => 2,"msg" => "操作数据库失败")));

} else if (strlen($_POST['nick']) < 2 || strlen($_POST['nick']) > 10) {

    die(json_encode(array("code" => 3,"msg" => "昵称长度非法")));

} else if (strlen($_POST['msg']) < 5 || strlen($_POST['msg']) > 100) {

    die(json_encode(array("code" => 4,"msg" => "留言内容非法")));

} else {

    $nick = $_POST['nick'];

    $msg = $_POST['msg'];

    $time = date('Y-m-d H:i:s');

    $query = mysqli_query($connect, "select avatar from users where nick='{$nick}';");

    if (!$query) exit();
    
    $avatar = mysqli_fetch_assoc($query)['avatar'];

    $query = mysqli_query($connect, "insert into msg values(null,'{$nick}','{$msg}','{$time}','{$avatar}');");
    
    if (!$query) {

        die(json_encode(array("code" => 5,"msg" => "操作数据库失败")));

    }

    die(json_encode(array("code" => 0,"msg" => "添加成功")));

}
